package event

import (
	"fmt"
	"gin-study/app/event/events"
	"gin-study/app/event/listeners"
)

const (
	EVENT_REGISTER = "Listen"
	EVENT_BOOT     = "boot"
	EVENT_SHUTDOWN = "shutdown"
)

var (
	Kernel *kernel
)

func init() {
	Kernel = &kernel{
		events: make(map[string][]listeners.Listener),
	}
	Kernel.Listen(new(events.Boot), new(listeners.Boot))
	Kernel.Listen(new(events.Shutdown), new(listeners.Shutdown))
	Kernel.Listen(new(events.Register), new(listeners.Register))
}

type kernel struct {
	events map[string][]listeners.Listener
}

//注册事件
func (this *kernel) Listen(event events.Event, listener listeners.Listener) {
	this.events[event.EventName()] = append(this.events[event.EventName()], listener)
}

//触发一个事件
func New(event events.Event) []error {
	list, hits := Kernel.events[event.EventName()]
	fmt.Println("事件:", event)
	if !hits {
		return nil
	}

	errs := make([]error, 1)
	for _, listener := range list {
		err := listener.Handle(event)
		if err != nil {
			errs = append(errs, err)
		}
	}
	return errs
}
